import { useState, useEffect } from "react";
import { TimingProps } from "@/types";

const useTiming = ({
  direction = "up",
  initialSeconds = 0,
  onDone,
}: TimingProps) => {
  const [isRunning, setIsRunning] = useState(false);
  const [seconds, setSeconds] = useState(initialSeconds);

  const resetTimer = () => {
    setSeconds(initialSeconds);
  }

  const startTimer = () => {
    setIsRunning(true);
  };

  const pauseTimer = () => {
    setIsRunning(false);
  };

  const stopTimer = () => {
    setIsRunning(false);
    setSeconds(0);
  };

  useEffect(() => {
    let interval: NodeJS.Timeout | undefined;

    if (isRunning && !interval) {
      interval = setInterval(() => {
        if (direction === "down" && seconds === 0) {
          clearInterval(interval);
          setIsRunning(false);
          onDone?.();
          return;
        }

        setSeconds((prev) => (direction === "up" ? prev + 1 : prev - 1));
      }, 1000);
    }

    return () => {
      if (interval) clearInterval(interval);
    };
  }, [isRunning, seconds]);

  return {
    isRunning,
    seconds,
    startTimer,
    pauseTimer,
    stopTimer,
    resetTimer
  };
};

export default useTiming;
